package team.freeroom.hotelmanage.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.*;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import javax.sql.DataSource;
import java.io.IOException;

/**
 * 酒店管理项目主配置类
 */
// 表明该类是配置类
@Configuration
// 获取 properties 文件中的数据
@PropertySource("classpath:application.properties")
// 扫描所有的 Bean 组件
@ComponentScan(value = {"team.freeroom.hotelmanage.repository", "team.freeroom.hotelmanage.service"})
// 扫描 MyBatis 的 Mapper 接口
@MapperScan("team.freeroom.hotelmanage.repository.mapper")
// 开启事务管理
@EnableTransactionManagement
public class ApplicationConfig {

    @Value("${jdbc.driver}")
    private String driver;
    @Value("${jdbc.url}")
    private String url;
    @Value("${jdbc.username}")
    private String username;
    @Value("${jdbc.password}")
    private String password;

    @Value("${mybatis.type.alias.package}")
    private String typeAliasesPackage;
    @Value("${mybatis.mapper.location}")
    private String mapperLocation;


    /**
     * 配置数据源 使用阿里数据库连接池
     */
    @Bean
    public DataSource dataSource() {
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setUsername(username);
        dataSource.setPassword(password);
        dataSource.setUrl(url);
        dataSource.setDriverClassName(driver);
        return dataSource;
    }

    /**
     * 配置mybatis的SqlSessionFactoryBean
     */
    @Bean
    public SqlSessionFactoryBean sqlSessionFactoryBean(DataSource dataSource) throws IOException {
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        // 设置数据源
        sqlSessionFactoryBean.setDataSource(dataSource);
        // 扫描 entity 包, 使用别名, 别名不区分大小写
        sqlSessionFactoryBean.setTypeAliasesPackage(typeAliasesPackage);
        // 扫描 SQL 映射的xml文件
        sqlSessionFactoryBean.setMapperLocations(
                new PathMatchingResourcePatternResolver()
                        .getResources(mapperLocation)
                // 注意: 这里是 getResources !!!
                // 如果是 getResource 只能指定一个文件, 通配符 * 无效
        );

        return sqlSessionFactoryBean;
    }

    /**
     * 配置 Spring 的声明式事务
     */
    @Bean
    public PlatformTransactionManager transactionManager(DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }
}
